﻿using CKS.Core.Framework;
using FreeSql;
using ImportPlcPointPosition.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZR.Model.Models.ProductionControl;

namespace CKS.PLC.Action.Subscription {

    /// <summary>
    /// 工作记录订阅点
    /// </summary>
    [SubscribeAction("EntryAndExitStationSubscribe")]
    public class EntryAndExitStationAction : SubscribeBase {

        public EntryAndExitStationAction(DecodeValue decodeValue) : base(decodeValue) {

        }

        /// <summary>
        /// 执行订阅动作的具体实现
        /// </summary>
        public override void ExecuteAction(Dictionary<string, object> execParams) {

            using (var ObjectCo = base.FreeSql.Ado.MasterPool.Get()) {
                var result = DecodeValue.Value.ToBool();
                var position = DecodeValue.Position;
                var conn = ObjectCo.Value;

                var act = conn.Select<CksPlcActions>()
                    .Where(a => a.ActionType == 1
                            && a.PlcId == position.PlcId
                            && a.ReadDB == position.BlockDb
                            && a.ActionKey == _saveResultRequestActionKey
                            )
                    .First();

                //更新工件记录
                if (result) {

                    var codevalue = GetMainCodeValue();
                    
                    if (codevalue.ToUpper().Contains("ERROR")) {
                        WriteLogUI("出入站加工信信号，扫码异常");
                        return;
                    }
                   
                    //获取工件记录
                    var cksWorkRec = conn.Select<CksWorkRecord>().Where(o => o.PlcID == DecodeValue.Position.PlcId && o.ReadDB == DecodeValue.Position.BlockDb && o.PrimaryCode == codevalue).ToList().LastOrDefault();
                    //获取工件采集记录
                    var cksCollectRec = conn.Select<CksCollected>().Where(o => o.PlcId == DecodeValue.Position.PlcId && o.ReadDB == DecodeValue.Position.BlockDb && o.PrimaryCode == codevalue).ToList().LastOrDefault();

                    if (cksWorkRec == null || cksCollectRec == null || DecodeValue.Position.LocationId == 2)
                    {//如果工件记录和采集记录都不存在，则新增工件记录

                        cksWorkRec = new CksWorkRecord();
                        cksWorkRec.PlcID = DecodeValue.Position.PlcId;
                        cksWorkRec.PrimaryCode = codevalue;
                        cksWorkRec.CreatedTime = DateTime.Now;
                        cksWorkRec.ReadDB = DecodeValue.Position.BlockDb; //设置读取DB块
                    }

                    string msg = string.Empty;
                    int res = 0;
                    switch (DecodeValue.Position.LocationId) {
                        case 1://工件入站
                            msg = "工件入站";
                            break;
                        case 2://生产开始
                            msg = "工件入站，生产开始";
                            cksWorkRec.MoveInTime = cksWorkRec.ProductionStartTime = DateTime.Now;
                            res = conn.Insert<CksWorkRecord>(cksWorkRec).ExecuteAffrows();
                            break;
                        case 3://生产结束
                            msg = "生产结束";
                            cksWorkRec.ProductionEndTime = DateTime.Now;
                            res = conn.Update<CksWorkRecord>().SetSource(cksWorkRec).ExecuteAffrows();
                            break;
                        case 4://工件离站
                            msg = "工件离站";
                            cksWorkRec.MoveOutTime = DateTime.Now;
                            res = conn.Update<CksWorkRecord>().SetSource(cksWorkRec).ExecuteAffrows();
                            break;
                        default:
                            break;
                    }

                    if (DecodeValue.Position.LocationId == 3 || DecodeValue.Position.LocationId == 4) {
                        //获取加工记录
                        cksWorkRec = conn.Select<CksWorkRecord>().Where(o => o.PlcID == DecodeValue.Position.PlcId && o.ReadDB == DecodeValue.Position.BlockDb && o.PrimaryCode == codevalue).ToList().LastOrDefault();

                        //获取虚拟表和列信息
                        var vTable = conn.Select<CksVirtualTable>().Where(a => a.Id == act.BusinessId).First();
                        //获取采集数据
                        var dataTable = base.FreeSql.Queryable<object>().AsTable((type, oldName) => {
                            return vTable.TableName;
                        }).Where("MainCode = '" + codevalue + "' and Nullity='0'").ToDataTable();
                        //获取最后一行数据
                        var row = dataTable.AsEnumerable().LastOrDefault();
                       
                        var dic = new Dictionary<string, object>();
                        dic.Add("Id", row["Id"]);
                        dic.Add("StartTime", cksWorkRec.ProductionStartTime);
                        dic.Add("EndTime", cksWorkRec.ProductionEndTime);
                        base.FreeSql.UpdateDict(dic).AsTable(vTable.TableName).WherePrimary("Id").ExecuteAffrows();
                    }

                    //如果条码值不为空，则保存工件记录
                    WriteLogUI($"保存进出站记录，{msg}，保存进出站记录，结果：{res > 0}");

                } else {

                    string msg = string.Empty;
                    switch (DecodeValue.Position.LocationId)
                    {
                        case 1://工件入站
                            msg = "工件入站";
                            break;
                        case 2://生产开始
                            msg = "工件入站，生产开始";
                            break;
                        case 3://生产结束
                            msg = "生产结束";
                            break;
                        case 4://工件离站
                            msg = "工件离站";
                            break;
                        default:
                            break;
                    }
                    WriteLogUI($"{msg}复位");
                }

            }
        }
    }

}
